<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统设置</title>
    <script src="common.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        h2 {
            color: #333;
            margin-bottom: 20px;
            text-align: center;
        }
        .setting-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f9f9f9;
        }
        .setting-item label {
            flex-basis: 150px;
            margin-right: 15px;
            font-weight: bold;
            color: #555;
        }
        .setting-item input[type="text"], .setting-item textarea {
            flex-grow: 1;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 14px;
        }
        .setting-item textarea {
            resize: vertical;
            min-height: 100px;
        }
        .button-group {
            text-align: center;
            margin-top: 20px;
        }
        .button-group button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }
        .button-group button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div id="message-area"></div>
    <div class="container">
        <h2>系统设置</h2>
        <div id="settingsList"></div>
        <div class="button-group">
            <button id="saveSettings">保存设置</button>
            <button id="refreshCache" style="margin-left: 10px;">刷新缓存</button>
        </div>
    </div>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const settingsListDiv = document.getElementById('settingsList');
            const saveSettingsBtn = document.getElementById('saveSettings');
            const refreshCacheBtn = document.getElementById('refreshCache');
            let settingsData = {}; // To store current settings for modification

            // Function to fetch and display settings
            async function fetchSettings() {
                try {
                    const response = await fetch('/settings/query');
                    const result = await response.json();

                    if (result.code === 0) {
                        settingsListDiv.innerHTML = ''; // Clear previous settings
                        settingsData = {}; // Reset settings data
                        result.data.forEach(setting => {
                            const settingItem = document.createElement('div');
                            settingItem.className = 'setting-item';
                            // 检查值的长度，如果超过50个字符则使用textarea
                            const isLongText = setting.value && setting.value.length > 50;
                            settingItem.innerHTML = `
                                <label for="${setting.key}">${setting.name}</label>
                                ${isLongText ? 
                                    `<textarea id="${setting.key}" data-key="${setting.key}">${setting.value}</textarea>` : 
                                    `<input type="text" id="${setting.key}" data-key="${setting.key}" value="${setting.value}">`
                                }
                            `;
                            settingsListDiv.appendChild(settingItem);
                            settingsData[setting.key] = setting.value; // Store initial value
                        });
                    } else {
                        showMessage('获取设置失败: ' + result.msg, 'error');
                    }
                } catch (error) {
                    console.error('Error fetching settings:', error);
                    showMessage('获取设置时发生错误。', 'error');
                }
            }

            // Function to save settings
            saveSettingsBtn.addEventListener('click', async function() {
                const inputs = settingsListDiv.querySelectorAll('[data-key]');
                for (const input of inputs) {
                    const key = input.dataset.key;
                    const newValue = input.value;

                    // Only send update if value has changed
                    if (settingsData[key] !== newValue) {
                        try {
                            const response = await fetch('/settings/update', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({ key: key, value: newValue })
                            });
                            const result = await response.json();

                            if (result.code !== 0) {
                                showMessage(`更新设置 ${key} 失败: ${result.msg}`, 'error');
                                // Optionally, re-fetch settings to show original values for failed updates
                                fetchSettings(); 
                                return; // Stop on first error
                            }
                        } catch (error) {
                            console.error(`Error updating setting ${key}:`, error);
                            showMessage(`更新设置 ${key} 时发生错误。`, 'error');
                            fetchSettings();
                            return; // Stop on first error
                        }
                    }
                }
                showMessage('所有设置已保存。');
                await fetchSettings();
                showMessage('缓存已刷新。', 'success');
            });

            // Function to refresh cache
            refreshCacheBtn.addEventListener('click', async function() {
                await fetchSettings();
                showMessage('缓存已刷新。', 'success');
            });

            // Initial fetch of settings
            fetchSettings();

            // 添加 Ctrl+S 快捷键监听
            document.addEventListener('keydown', function(event) {
                if ((event.ctrlKey || event.metaKey) && event.key === 's') {
                    event.preventDefault();
                    saveSettingsBtn.click();
                }
            });
        });
    </script>
</body>
</html>